package leetcode;

import java.util.HashMap;

public class WordPattern {

	public static void main(String[] args) {
		WordPattern wordPattern = new WordPattern();
		System.out.println(wordPattern.wordPattern("aaaa", "dog cat cat dog"));
		System.out.println(wordPattern.wordPattern("abba", "dog dog dog dog"));
	}
	
	//Here follow means a full match, such that there is a bijection between a letter in pattern 
	//and a non-empty word in str
	//pattern = "abba", str = "dog cat cat dog" 
	//a映射到dog，b映射到cat
	public boolean wordPattern(String pattern, String str) {
		if (pattern == null || str == null) {
			return str == null;
		}
		String[] words = str.split(" ");
		int length = pattern.length();
		if (words.length != length) {
			return false;
		}
		//建立两个hashmap来判断是否是同样的映射
		HashMap<Character, String> map = new HashMap<>();
		HashMap<String, Character> reMap = new HashMap<>();
		String temp = "";
		for (int i = 0; i < length; i++) {
			if (map.containsValue(words[i])){
				if(reMap.get(words[i]) != pattern.charAt(i)){
					return false;
				}
			}
			if ((temp = map.get(pattern.charAt(i))) == null) {
				map.put(pattern.charAt(i), words[i]);
				reMap.put(words[i], pattern.charAt(i));
			} else {
				if (!temp.equals(words[i])) {
					return false;
				}
			}
		}
		// for(int i = 0; i < length / 2; i++){
		// if( (pattern.charAt(i) == pattern.charAt(length - 1 - i) &&
		// !words[i].equals(words[length - 1 - i])) ||
		// (pattern.charAt(i) != pattern.charAt(length - 1 - i) &&
		// words[i].equals(words[length - 1 - i]))){
		// return false;
		// }
		// }
		return true;
	}
}
